package CustomUI;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.Consts;
import org.Globals;
import org.json.JSONException;
import org.json.JSONObject;

import com.ydev.graphics.animations.R;

import DTO.GradientsDTO;
import GameTools.ydPoint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Bitmap.Config;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TabHost;
import android.widget.TextView;

public class CopyOfydCustomColorPicker extends Dialog {

	ydPoint size;
	
	public CopyOfydCustomColorPicker(Context context) {
		super(context);
		
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.color_dialog_layout);
		//setContentView(R.layout.color_dialog);
		
		//ydColorLineMinor minor= (ydColorLineMinor)findViewById(R.id.ydColorLineMinor1);
		//init();
		// TODO Auto-generated constructor stub
	}

	public CopyOfydCustomColorPicker(Context context, int theme) {
		super(context, theme);
		// TODO Auto-generated constructor stub
	}

	public CopyOfydCustomColorPicker(Context context, boolean cancelable,
			OnCancelListener cancelListener) {
		super(context, cancelable, cancelListener);
		// TODO Auto-generated constructor stub
	}
	
	LinearLayout tabLayout= new LinearLayout(this.getContext());
	
	LinearLayout l1= new LinearLayout(this.getContext());
	LinearLayout colorPicker= new LinearLayout(this.getContext());
	LinearLayout l3= new LinearLayout(this.getContext());
	LinearLayout colorSliders= new LinearLayout(this.getContext());
	LinearLayout favouriteColors= new LinearLayout(this.getContext());
	LinearLayout l5= new LinearLayout(this.getContext());
	RelativeLayout r1= new RelativeLayout(this.getContext());

	String tag="{\"veiw_tags_toggle\": \"true\",\"veiw_tags_action\": \"drawing_action_brush\",\"veiw_tags_shape\": \"circle\"}";
	
	ydButton tab1= new ydButton(getContext(), tag);
	ydButton tab2= new ydButton(getContext(), tag);
	
	ydColorLineMajor s1= new ydColorLineMajor(this.getContext());
	ydColorLineMinor s2= new ydColorLineMinor(this.getContext());
	
	SeekBar sbRed=new SeekBar(this.getContext());
	SeekBar sbGreen=new SeekBar(this.getContext());
	SeekBar sbBlue=new SeekBar(this.getContext());
	SeekBar sbAlpha=new SeekBar(this.getContext());
	
	View v1 = new View(this.getContext());
	Button b1 = new Button(this.getContext());
	
	int c1=0;
	
    MainThread mt=new MainThread(this);
	
	public void init(){
		
		l1.setOrientation(LinearLayout.VERTICAL);
	    l1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	    l1.setBackgroundResource(R.drawable.dialog_bg_med);
	    
	    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	    
	  //  this.setTitle(\"TESTING\");
	   // LinearLayout l1= new LinearLayout(this.getContext());
	    //l1=(LinearLayout)findViewById(R.id.llMain);
	  // 	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		//this.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
	 //   this.addContentView(l1, l1.getLayoutParams());
	    
	//    act=this.getOwnerActivity();
	    
	    return;
	    
	}
	ArrayList<Bitmap> bitmaps=new ArrayList<Bitmap>();
	private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
	    @Override
	    protected String doInBackground(String... urls) {
	    	//android.os.Debug.waitForDebugger();
	      String response = "";
			for(int i=0; i<255; i++){
				Log.d("INthread", i+ " ");
				  s2.setHue(i);
		  			s1.updateCurrentSelectedColor(s2.getCurrentHue());


			publishProgress();
			GradientsDTO grad=new GradientsDTO();
			grad.hue=s2.getCurrentHue();
			Log.d("CUrrent hue",grad.hue+ " ");
			grad.image = Bitmap.createBitmap(255, 255, Bitmap.Config.ARGB_8888);
			s1.onDraw(new Canvas(grad.image));
			grad.insertIntoDatabase(Globals.sqlDB);
			}
	      return response;
	    }
	    

	    @Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			act.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					s2.invalidate();
				s1.invalidate();
					
				}
			});
			
			
			//Bitmap myBitmap = new Bitmap(255, 255, Bitmap.Config.RGB_565);
			//s1.mCanvas.setBitmap(myBitmap);
		}

		@Override
	    protected void onPostExecute(String result) {
	    	
	      //textView.setText(result);
	    }
	  }
	
	  Activity act;
int i=0;
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub
		super.onWindowFocusChanged(hasFocus);
		
	//	this.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
		
size=new ydPoint(this.getWindow().getDecorView().getWidth(), this.getWindow().getDecorView().getHeight());
		
		ydPoint setSize=new ydPoint();
		
LinearLayout llTest=(LinearLayout)findViewById(R.id.llTest);
LinearLayout.LayoutParams addQuestion_Params = 
new LinearLayout.LayoutParams((int)(size.x*.7), (int)(size.x*.7));  
		llTest.setLayoutParams(addQuestion_Params);
		
		
		
		/*LayoutParams lpt=new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		lpt.setMargins(30, 45, 30,10);
		
		
		tabLayout.setOrientation(LinearLayout.HORIZONTAL);
		tabLayout.setLayoutParams(lpt);
		tabLayout.setBackgroundColor(Color.TRANSPARENT);
		
		lpt=new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
	    lpt.weight=1;
		
	    tab1.setTag("{\"veiw_tags_toggle\": \"true\",\"veiw_tags_action\": \"drawing_action_brush\",\"veiw_tags_shape\": \"circle\"}");
		tab1.setBackgroundResource(R.drawable.tabs_color_picker);
	    tab1.setLayoutParams(lpt);
		
	    tab2.setTag("{\"veiw_tags_toggle\": \"true\",\"veiw_tags_action\": \"drawing_action_brush\",\"veiw_tags_shape\": \"circle\"}");
		tab2.setBackgroundResource(R.drawable.tabs_color_sliders);
	    tab2.setLayoutParams(lpt);
	    
	    tabLayout.addView(tab1);
	    tabLayout.addView(tab2);
	    
	    setTabsAction();
	    tabClicked(tab1);
	    
	    colorPicker.setOrientation(LinearLayout.HORIZONTAL);
	    l3.setOrientation(LinearLayout.HORIZONTAL);
	    
	    colorSliders.setOrientation(LinearLayout.VERTICAL);
	    l5.setOrientation(LinearLayout.VERTICAL);
	    
	    l1.addView(tabLayout);
	    l1.addView(colorPicker);
	    l1.addView(colorSliders);
	    l1.addView(l3);
	    
	    colorSliders.setVisibility(View.GONE);
	    
	    favouriteColors.setLayoutParams(new LayoutParams((int)setSize.x,LayoutParams.FILL_PARENT));
	    l3.addView(favouriteColors);
	    l3.addView(l5);
	    final Activity act=this.getOwnerActivity();
	    Button btn= new Button(getContext());
	    btn.setText("save");
	    btn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Log.d("Save CLicked", " EXexcute async");
				 DownloadWebPageTask task = new DownloadWebPageTask();
				    task.execute();
				
			i=0;
			mt.running=true;
				mt.start();
				
			}
		});
	    favouriteColors.addView(btn);
		
		setSize.x=(float) ((size.x-20*2-10)*0.8);
		setSize.y=setSize.x;
		
		LayoutParams layoutParams=new LayoutParams((int)setSize.x, (int)setSize.y);
	    layoutParams.setMargins(40, 0, 0, 0);
	    s1.setSize(new ydPoint(255, 255));
		s1.setBackgroundColor(Color.TRANSPARENT);
		s1.setLayoutParams(layoutParams);
		colorPicker.addView(s1);
		
		setSize.x=(float) ((size.x-20*2-10)*0.1);
		
		layoutParams=new LayoutParams((int)setSize.x, (int)setSize.y);
	    layoutParams.setMargins(20, 0, 0, 0);
	    s2.setSize(new ydPoint(255, 255));
	    s2.setBackgroundColor(Color.TRANSPARENT);
		s2.setLayoutParams(layoutParams);
		colorPicker.addView(s2);
		
		setTouchListeners();
		
		layoutParams=new LayoutParams((int)setSize.y, (int)setSize.x);
	    layoutParams.setMargins(40, 5, 0, 0);
	    sbRed.setMax(255);
	    sbRed.setBackgroundColor(Color.RED);
	    sbRed.setLayoutParams(layoutParams);
		colorSliders.addView(sbRed);
		
		layoutParams=new LayoutParams((int)setSize.y, (int)setSize.x);
	    layoutParams.setMargins(40, 5, 0, 0);
	    sbGreen.setMax(255);
	    sbGreen.setBackgroundColor(Color.GREEN);
	    sbGreen.setLayoutParams(layoutParams);
		colorSliders.addView(sbGreen);
		
		layoutParams=new LayoutParams((int)setSize.y, (int)setSize.x);
	    layoutParams.setMargins(40, 5, 0, 0);
	    sbBlue.setMax(255);
	    sbBlue.setBackgroundColor(Color.BLUE);
	    sbBlue.setLayoutParams(layoutParams);
		colorSliders.addView(sbBlue);
		
		layoutParams=new LayoutParams((int)setSize.y, (int)setSize.x);
	    layoutParams.setMargins(40, 5, 0, 0);
	    sbAlpha.setMax(255);
	    sbAlpha.setBackgroundColor(Color.BLACK);
	    sbAlpha.setLayoutParams(layoutParams);
		colorSliders.addView(sbAlpha);
		
		setSeekListeners();
		updateColor();
		
		layoutParams=new LayoutParams((int)setSize.x, (int)setSize.x);
	    layoutParams.setMargins(20, 5, 0, 0);
	    v1.setBackgroundColor(c1);
	    v1.setLayoutParams(layoutParams);
		//l5.addView(btn);
*/		
		return;
	}
	
	private void setTabsAction() {
/*		tab1.addOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				tabClicked(tab1);

			}
		});
		
		tab2.addOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				tabClicked(tab2);

			}
		});*/
		setTabClicked(tab1);
		setTabClicked(tab2);
		
	}

	private void setTabClicked(final ydButton btn) {
		btn.addOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				tabClicked(btn);

			}
		});
		
	}

	protected void tabClicked(ydButton btn) {
		JSONObject obj = null;
		try {
			obj = new JSONObject((String) btn.getTag());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (obj.optString(Consts.VIEW_TAGS_TOGGLE).equals("true")) {
			tab1.setSelected(false);
			tab2.setSelected(false);


			btn.setSelected(true);

			Log.d("Button CLicked", btn.toString());

			if(tab1.isSelected()){
				colorPicker.setVisibility(View.VISIBLE);
				colorSliders.setVisibility(View.GONE);
			}
			else if(tab2.isSelected()){
				colorPicker.setVisibility(View.GONE);
				colorSliders.setVisibility(View.VISIBLE);
			}
		}
		
		
	}

	private void setTouchListeners() {
		s2.listeners.addOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				s1.updateCurrentSelectedColor(s2.getCurrentHue());
				//s1.setColor(r,g,b);
				//s1.setCurrentHue(s2.getCurrentHue());
				//s1.setChangeMade(true);
				return true;
			}
		});
		
	}

	public void updateColor(){
		c1=Color.argb(sbAlpha.getProgress(), sbRed.getProgress(), sbGreen.getProgress(), sbBlue.getProgress());
	}
	
	public void setSeekListeners(){
		setSeekListener(sbRed);
		setSeekListener(sbGreen);
		setSeekListener(sbBlue);
		setSeekListener(sbAlpha);
	}
	
	public void setSeekListener(SeekBar s){
		s.setProgress(255);
		s.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {       

		    @Override       
		    public void onStopTrackingTouch(SeekBar seekBar) {      
		        // TODO Auto-generated method stub      
		    }       

		    @Override       
		    public void onStartTrackingTouch(SeekBar seekBar) {     
		        // TODO Auto-generated method stub      
		    }       

		    @Override       
		    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {     
		        // TODO Auto-generated method stub      
		        updateColor();
		        v1.setBackgroundColor(c1);

		    }       
		});             
	}
	
	public void update() {
		Log.d("CUrrent frame",i+ " ");
		  s2.setHue(i);
			s1.updateCurrentSelectedColor(s2.getCurrentHue());

			s2.postInvalidate();
			s1.postInvalidate();
	GradientsDTO grad=new GradientsDTO();
	grad.hue=s2.getCurrentHue();
	Log.d("CUrrent hue",grad.hue+ " ");
	grad.image = Bitmap.createBitmap(255, 255, Bitmap.Config.ARGB_8888);
	s1.onDraw(new Canvas(grad.image));
	grad.insertIntoDatabase(Globals.sqlDB);
		i++;
	}
	
	public class MainThread extends Thread {
		
		
		// desired fps
		private final static int 	MAX_FPS = 1;	
		// maximum number of frames to be skipped
		private final static int	MAX_FRAME_SKIPS = 5;	
		// the frame period
		private final static int	FRAME_PERIOD = 1000 / MAX_FPS;	

		// Surface holder that can access the physical surface
		// The actual view that handles inputs
		// and draws to the surface
		private CopyOfydCustomColorPicker gamePanel;

		// flag to hold game state 
		private boolean running;
		public void setRunning(boolean running) {
			this.running = running;
		}

		public MainThread( CopyOfydCustomColorPicker gamePanel) {
			super();
		
			this.gamePanel = gamePanel;
		}

		@Override
		public void run() {
			Canvas canvas;
			Log.d("Game LOpp", "Starting game loop");

			long beginTime;		// the time when the cycle begun
			long timeDiff;		// the time it took for the cycle to execute
			int sleepTime;		// ms to sleep (<0 if we're behind)
			int framesSkipped;	// number of frames being skipped 

			sleepTime = 0;
			
			while (running) {

				try {
					
						beginTime = System.currentTimeMillis();
						framesSkipped = 0;	// resetting the frames skipped
						// update game state 
						this.gamePanel.update();
						// render state to the screen
						// draws the canvas on the pane			
						// calculate how long did the cycle take
						timeDiff = System.currentTimeMillis() - beginTime;
						// calculate sleep time
						sleepTime = (int)(FRAME_PERIOD - timeDiff);
						
						
							// if sleepTime > 0 we're OK
							try {
								// send the thread to sleep for a short period
								// very useful for battery saving
								Thread.sleep(1000);	
							} catch (InterruptedException e) {}
						

					}
				 finally {
					// in case of an exception the surface is not left in 
					// an inconsistent state
	
				}	// end finally
			}
		}
	
	}
}

	
